<template>
  <view class="config-form">
    <view class="form-header">
      <text class="form-title">抢夺配置</text>
      <text class="nickname-count">目标昵称: {{ config.nicknames?.length || 0 }}</text>
    </view>
    <view class="form-content">
      <!-- 目标昵称输入 -->
      <view class="form-item">
        <text class="form-label">目标昵称 (每行一个)</text>
        <textarea
          v-model="nicknameInput"
          class="nickname-textarea"
          placeholder="输入目标昵称，每行一个"
          :disabled="isRunning"
          @input="handleInput"
          :maxlength="-1"
          :show-confirm-bar="false"
          :cursor-spacing="20"
          :adjust-position="false"
          :hold-keyboard="true"
        />
        <view class="nickname-actions">
          <button
            class="action-button clear-button"
            :disabled="isRunning || !config.nicknames?.length"
            @click="clearNicknames"
          >
            清空昵称
          </button>
        </view>
      </view>
      <!-- 其他配置项 -->
      <view class="form-item">
        <text class="form-label">灵石阈值</text>
        <input
          type="number"
          v-model="config.threshold"
          class="form-input"
          placeholder="请输入灵石阈值"
          :disabled="isRunning"
          @blur="emitConfig"
        />
      </view>
      <view class="form-item">
        <text class="form-label">Role ID</text>
        <input
          type="text"
          v-model="config.roleId"
          class="form-input"
          placeholder="请输入 Role ID"
          :disabled="isRunning"
          @blur="emitConfig"
        />
      </view>
      <view class="form-item">
        <text class="form-label">Token</text>
        <textarea
          v-model="config.token"
          class="token-textarea"
          placeholder="请输入 Token"
          :disabled="isRunning"
          @blur="handleTokenChange"
          :maxlength="-1"
          :show-confirm-bar="false"
          :cursor-spacing="20"
          :adjust-position="false"
          :hold-keyboard="true"
        />
      </view>
      <view class="form-item">
        <text class="form-label">快速刷新次数</text>
        <input
          type="number"
          v-model="config.quickRefreshCount"
          class="form-input"
          placeholder="请输入快速刷新次数"
          :disabled="isRunning"
          @blur="emitConfig"
        />
      </view>
      <view class="form-item">
        <text class="form-label">快速刷新持续时间 (秒)</text>
        <input
          type="number"
          v-model="config.quickRefreshDuration"
          class="form-input"
          placeholder="请输入快速刷新持续时间"
          :disabled="isRunning"
          @blur="emitConfig"
        />
      </view>
      <view class="form-item">
        <text class="form-label">快速刷新间隔 (秒)</text>
        <input
          type="number"
          v-model="config.quickRefreshInterval"
          class="form-input"
          placeholder="请输入快速刷新间隔"
          :disabled="isRunning"
          @blur="emitConfig"
        />
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, watch, onMounted } from 'vue';

const props = defineProps({
  isRunning: {
    type: Boolean,
    default: false
  },
  initialConfig: {
    type: Object,
    required: true,
    default: () => ({
      nicknames: [],
      uid: '',
      roleId: '',
      token: '',
      threshold: '168.0',
      quickRefreshCount: '3',
      quickRefreshDuration: '40',
      quickRefreshInterval: '4',
      startTime: '10:00',
      stopTime: '19:00'
    })
  }
});

const emit = defineEmits(['update:config']);

// 本地状态初始化
const config = ref({
  nicknames: [],
  uid: '',
  roleId: '',
  token: '',
  threshold: '168.0',
  quickRefreshCount: '3',
  quickRefreshDuration: '40',
  quickRefreshInterval: '4',
  startTime: '10:00',
  stopTime: '19:00'
});

const nicknameInput = ref('');
let inputTimer = null;

// 处理输入，使用防抖
const handleInput = (e) => {
  if (inputTimer) {
    clearTimeout(inputTimer);
  }
  inputTimer = setTimeout(() => {
    updateNicknames();
  }, 300);
};

// 初始化配置
onMounted(() => {
  if (props.initialConfig) {
    // 确保 nicknames 是数组
    const initialNicknames = Array.isArray(props.initialConfig.nicknames) 
      ? props.initialConfig.nicknames 
      : [];
    
    config.value = {
      ...props.initialConfig,
      nicknames: initialNicknames
    };
    
    // 直接使用原始昵称数组
    nicknameInput.value = initialNicknames.join('\n');
    console.log('初始化昵称数量:', initialNicknames.length);
  }
});

// 监听配置变化
watch(() => props.initialConfig, (newConfig) => {
  if (newConfig) {
    console.log('收到新的初始配置:', {
      hasToken: !!newConfig.token,
      tokenLength: newConfig.token?.length,
      tokenValue: newConfig.token ? newConfig.token.substring(0, 20) + '...' : null
    });

    // 确保 nicknames 是数组
    const newNicknames = Array.isArray(newConfig.nicknames) 
      ? newConfig.nicknames 
      : [];
    
    config.value = {
      ...newConfig,
      nicknames: newNicknames,
      token: newConfig.token?.trim() || '' // 确保 token 被正确处理
    };
    
    // 直接使用原始昵称数组
    nicknameInput.value = newNicknames.join('\n');
    console.log('更新配置完成:', {
      hasToken: !!config.value.token,
      tokenLength: config.value.token?.length,
      tokenValue: config.value.token ? config.value.token.substring(0, 20) + '...' : null,
      nicknamesCount: newNicknames.length
    });
  }
}, { deep: true, immediate: true });

// 更新昵称列表
const updateNicknames = () => {
  if (!nicknameInput.value) {
    config.value.nicknames = [];
    emitConfig();
    return;
  }

  try {
    // 直接使用换行符分割，不做任何处理
    const nicknames = nicknameInput.value.split('\n');
    console.log('处理昵称数量:', nicknames.length);
    
    // 更新配置
    config.value.nicknames = nicknames;
    emitConfig();
  } catch (e) {
    console.error('更新昵称失败:', e);
  }
};

// 清空昵称
const clearNicknames = () => {
  uni.showModal({
    title: '确认清空',
    content: '确定要清空所有目标昵称吗？',
    success: (res) => {
      if (res.confirm) {
        config.value.nicknames = [];
        nicknameInput.value = '';
        emitConfig();
      }
    }
  });
};

// 处理 token 变化
const handleTokenChange = () => {
  const token = config.value.token?.trim() || '';
  console.log('Token 变化:', {
    exists: !!token,
    length: token.length,
    value: token.substring(0, 20) + '...' // 只显示前20个字符
  });

  if (!token) {
    console.log('Token 为空，清空 uid');
    config.value.uid = '';
    emitConfig();
    return;
  }

  try {
    // 只尝试提取 uid，不做任何验证
    const parts = token.split('.');
    if (parts.length >= 2) {
      const payloadPart = parts[1];
      if (payloadPart) {
        try {
          // 将 URL 安全的 base64 转换为标准 base64
          const standardBase64 = payloadPart.replace(/-/g, '+').replace(/_/g, '/');
          // 添加 padding
          const paddedBase64 = standardBase64 + '='.repeat((4 - standardBase64.length % 4) % 4);
          // 解码
          const decodedPayload = decodeURIComponent(escape(atob(paddedBase64)));
          // 从解码后的 payload 中提取 jti
          const match = decodedPayload.match(/"jti"\s*:\s*"(\d+)"/);
          if (match) {
            config.value.uid = match[1];
            console.log('提取到 UID:', config.value.uid);
          }
        } catch (e) {
          console.log('提取 UID 失败:', e.message);
        }
      }
    }
    emitConfig();
  } catch (e) {
    console.error('处理 token 失败:', e);
    emitConfig();
  }
};

// 发射配置更新
const emitConfig = () => {
  try {
    // 确保发送完整的配置
    const updatedConfig = {
      ...config.value,
      nicknames: config.value.nicknames || [],
      token: config.value.token?.trim() || '' // 确保 token 被正确处理
    };
    console.log('发送配置:', {
      hasToken: !!updatedConfig.token,
      tokenLength: updatedConfig.token?.length,
      tokenValue: updatedConfig.token ? updatedConfig.token.substring(0, 20) + '...' : null,
      nicknamesCount: updatedConfig.nicknames.length
    });
    emit('update:config', updatedConfig);
  } catch (e) {
    console.error('发送配置失败:', e);
  }
};
</script>

<style>
.config-form {
  background: #f8f9fa;
  border-radius: 8rpx;
  padding: 12rpx;
  margin: 12rpx 0;
}

.form-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8rpx;
}

.form-title {
  font-size: 24rpx;
  font-weight: 600;
  color: #2c3e50;
}

.nickname-count {
  font-size: 20rpx;
  color: #909399;
}

.form-content {
  display: flex;
  flex-direction: column;
  gap: 8rpx;
}

.form-item {
  display: flex;
  flex-direction: column;
  gap: 4rpx;
}

.form-label {
  font-size: 20rpx;
  color: #606266;
}

.nickname-textarea {
  background: white;
  border: 1rpx solid #dcdfe6;
  border-radius: 4rpx;
  padding: 6rpx;
  font-size: 22rpx;
  color: #2c3e50;
  height: 120rpx;
  width: 100%;
  box-sizing: border-box;
  white-space: pre-wrap;
  word-break: break-all;
  overflow-y: auto;
  -webkit-overflow-scrolling: touch;
  will-change: transform;
  transform: translateZ(0);
  line-height: 1.3;
}

.form-input {
  background: white;
  border: 1rpx solid #dcdfe6;
  border-radius: 4rpx;
  padding: 8rpx;
  font-size: 22rpx;
  color: #2c3e50;
}

.nickname-actions {
  display: flex;
  justify-content: flex-end;
  margin-top: 4rpx;
}

.action-button {
  padding: 6rpx 12rpx;
  font-size: 20rpx;
  border-radius: 4rpx;
  border: none;
  transition: all 0.2s ease;
}

.clear-button {
  background: #f56c6c;
  color: white;
}

.clear-button:disabled {
  background: #f4f4f5;
  color: #c0c4cc;
}

.clear-button:active {
  transform: translateY(1rpx);
}

.token-textarea {
  background: white;
  border: 1rpx solid #dcdfe6;
  border-radius: 4rpx;
  padding: 8rpx;
  font-size: 22rpx;
  color: #2c3e50;
  height: 100rpx;
  width: 100%;
  box-sizing: border-box;
  white-space: pre-wrap;
  word-break: break-all;
  overflow-y: auto;
  -webkit-overflow-scrolling: touch;
  will-change: transform;
  transform: translateZ(0);
  font-family: monospace;
}

@media screen and (min-width: 768px) {
  .config-form {
    max-width: 500rpx;
  }

  .nickname-textarea {
    height: 160rpx;
  }

  .token-textarea {
    height: 140rpx;
  }
}
</style>